package mo.tags.queue;

import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;

public class NestedIterator implements Iterator<Integer> {

    private Queue<NestedInteger> queue = new ArrayDeque<>();

    public NestedIterator(List<NestedInteger> nestedList) {
        for (NestedInteger nestedInteger : nestedList) {
            addToQueue(nestedInteger);
        }
    }


    private void addToQueue(NestedInteger nestedInteger) {
        if (nestedInteger.isInteger()) {
            queue.add(nestedInteger);
        } else {
            for (NestedInteger e : nestedInteger.getList()) {
                addToQueue(e);
            }
        }
    }

    @Override
    public Integer next() {
        return queue.poll().getInteger();
    }

    @Override
    public boolean hasNext() {
        return !queue.isEmpty();
    }



    public interface NestedInteger {

        // @return true if this NestedInteger holds a single integer, rather than a nested list.
        public boolean isInteger();

        // @return the single integer that this NestedInteger holds, if it holds a single integer
        // Return null if this NestedInteger holds a nested list
        public Integer getInteger();

        // @return the nested list that this NestedInteger holds, if it holds a nested list
        // Return empty list if this NestedInteger holds a single integer
        public List<NestedInteger> getList();
    }
}




